import json
import json
import os
import logging
from collections import defaultdict
from typing import Dict, List, Optional, Any
from datetime import datetime

# 导入Neo4j服务
try:
    from ..services.neo4j_service import neo4j_service
    NEO4J_AVAILABLE = True
except ImportError as e:
    logging.warning(f"Neo4j服务导入失败: {str(e)}，将禁用知识图谱功能")
    NEO4J_AVAILABLE = False
    neo4j_service = None

# 导入深度学习相关模块
try:
    from .qa_trainer import MedicalQATrainer
    from ..utils.auto_learning import get_auto_learning_manager
    from ..utils.model_evaluator import MedicalQAEvaluator
    DEEP_LEARNING_AVAILABLE = True
except ImportError as e:
    logging.warning(f"深度学习模块导入失败: {str(e)}，将使用基础问答功能")
    DEEP_LEARNING_AVAILABLE = False

class MedicalQAModel:
    def __init__(self, use_deep_learning: bool = True, use_neo4j: bool = True):
        self.diseases_data = {}
        self.departments_data = {}
        self.knowledge_graph = {}
        self.use_deep_learning = use_deep_learning and DEEP_LEARNING_AVAILABLE
        self.use_neo4j = use_neo4j and NEO4J_AVAILABLE
        
        # 深度学习模型相关
        self.dl_trainer = None
        self.auto_learning_manager = None
        self.evaluator = None
        self.model_loaded = False
        
        # Neo4j服务
        self.neo4j_service = neo4j_service if self.use_neo4j else None
        
        # 统计信息
        self.query_count = 0
        self.feedback_count = 0
        
        self._load_data()
        
        # 初始化深度学习组件
        if self.use_deep_learning:
            self._initialize_deep_learning_components()
        
    def _load_data(self):
        """
        加载医疗数据
        Load medical data from JSON files
        """
        try:
            # Load medical data
            medical_data_path = os.path.join(os.path.dirname(__file__), '..', 'data', 'medical_data.json')
            if os.path.exists(medical_data_path):
                with open(medical_data_path, 'r', encoding='utf-8') as f:
                    medical_data = json.load(f)
                    
                # Process diseases data
                for disease in medical_data.get('diseases', []):
                    self.diseases_data[disease['name']] = disease
                    
                # Process departments data
                for department in medical_data.get('departments', []):
                    self.departments_data[department['name']] = department
            
            # Load knowledge graph
            kg_path = os.path.join(os.path.dirname(__file__), '..', 'data', 'knowledge_graph.json')
            if os.path.exists(kg_path):
                with open(kg_path, 'r', encoding='utf-8') as f:
                    self.knowledge_graph = json.load(f)
                    
            logging.info("Medical data loaded successfully")
        except Exception as e:
            logging.error(f"Failed to load medical data: {str(e)}")
            raise
    
    def _initialize_deep_learning_components(self):
        """初始化深度学习组件"""
        try:
            # 初始化评估器
            self.evaluator = MedicalQAEvaluator()
            
            # 初始化自主学习管理器
            data_dir = os.path.join(os.path.dirname(__file__), '..', 'data')
            self.auto_learning_manager = get_auto_learning_manager(data_dir)
            
            # 尝试加载已训练的模型
            self._load_trained_model()
            
            logging.info("深度学习组件初始化成功")
            
        except Exception as e:
            logging.error(f"深度学习组件初始化失败: {str(e)}")
            self.use_deep_learning = False
    
    def _load_trained_model(self):
        """加载已训练的深度学习模型"""
        try:
            model_path = os.path.join(os.path.dirname(__file__), '..', '..', 'models', 'medical_qa')
            
            if os.path.exists(model_path):
                self.dl_trainer = MedicalQATrainer()
                self.dl_trainer.load_trained_model(model_path)
                self.model_loaded = True
                logging.info("已训练的深度学习模型加载成功")
            else:
                logging.info("未找到已训练的模型，将使用基础问答功能")
                
        except Exception as e:
            logging.error(f"加载深度学习模型失败: {str(e)}")
            self.model_loaded = False
    
    def _query_knowledge_graph(self, question: str) -> Dict[str, Any]:
        """
        增强的Neo4j知识图谱查询
        Enhanced Neo4j knowledge graph query
        
        Args:
            question: 用户问题
            
        Returns:
            知识图谱查询结果
        """
        if not self.use_neo4j or not self.neo4j_service:
            return {'diseases': [], 'symptoms': [], 'drugs': [], 'departments': [], 'relationships': []}
            
        try:
            question_type, keywords = self._analyze_question(question)
            
            if not keywords:
                return self._query_general_knowledge(question)
            
            # 增强的查询策略：多关键词组合查询
            results = {}
            
            # 根据问题类型选择最优查询策略
            if question_type == 'disease_symptoms':
                results = self._query_disease_symptoms_enhanced(keywords)
            elif question_type == 'symptom_diseases':
                results = self._query_symptom_diseases_enhanced(keywords)
            elif question_type == 'disease_treatment':
                results = self._query_disease_treatment_enhanced(keywords)
            elif question_type == 'department_recommendation':
                results = self._query_department_recommendation_enhanced(keywords)
            elif question_type == 'drug_information':
                results = self._query_drug_information_enhanced(keywords)
            elif question_type == 'prevention':
                results = self._query_prevention_enhanced(keywords)
            else:
                results = self._query_general_knowledge_enhanced(question, keywords)
            
            # 增强结果验证
            if results and self._validate_kg_results(results):
                return results
            else:
                # 回退到基础查询
                return self._fallback_kg_query(question, keywords)
                
        except Exception as e:
            logging.error(f"知识图谱查询失败: {str(e)}")
            return {'diseases': [], 'symptoms': [], 'drugs': [], 'departments': [], 'relationships': []}
    
    def _analyze_question(self, question: str) -> tuple:
        """
        增强的问题分析和关键词提取
        Enhanced question analysis and keyword extraction
        """
        import re
        question_lower = question.lower().strip()
        keywords = []
        
        # 清理问题文本
        question_clean = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', question_lower)
        
        # 提取疾病名称（支持模糊匹配）
        for disease_name in self.diseases_data.keys():
            disease_lower = disease_name.lower()
            if disease_lower in question_lower or any(word in disease_lower for word in question_clean):
                keywords.append(disease_name)
        
        # 提取症状（支持同义词匹配）
        all_symptoms = set()
        for disease_info in self.diseases_data.values():
            all_symptoms.update(disease_info.get('symptoms', []))
        
        # 症状同义词映射
        symptom_synonyms = {
            '发烧': ['发热', '高烧', '低烧', '体温升高'],
            '咳嗽': ['干咳', '咳痰', '咳嗽不止'],
            '头痛': ['头疼', '头晕', '头部疼痛'],
            '腹痛': ['肚子疼', '胃疼', '肚子痛'],
            '恶心': ['想吐', '反胃', '作呕']
        }
        
        for symptom in all_symptoms:
            symptom_lower = symptom.lower()
            if symptom_lower in question_lower:
                keywords.append(symptom)
            else:
                # 检查同义词
                for main_symptom, synonyms in symptom_synonyms.items():
                    if symptom_lower == main_symptom:
                        for synonym in synonyms:
                            if synonym in question_lower:
                                keywords.append(symptom)
                                break
        
        # 提取科室（支持模糊匹配）
        for dept_name in self.departments_data.keys():
            dept_lower = dept_name.lower()
            if dept_lower in question_lower:
                keywords.append(dept_name)
        
        # 增强的问题类型识别
        question_patterns = {
            'disease_symptoms': [
                r'.*?(症状|表现|临床表现|征象|体征|有什么症状|有哪些症状)',
                r'.*?得了.*?什么.*?症状',
                r'.*?会出现.*?什么.*?表现'
            ],
            'symptom_diseases': [
                r'.*?(可能是|是什么|什么病|什么疾病|得了什么|引起|导致)',
                r'.*?有.*?症状.*?是什么病',
                r'.*?出现.*?可能.*?什么病'
            ],
            'disease_treatment': [
                r'.*?(治疗|用药|药物|医治|疗法|方案|吃什么药|用什么药|怎么治疗|如何治疗)',
                r'.*?治.*?好|治好',
                r'.*?需要.*?治疗'
            ],
            'department_recommendation': [
                r'.*?(挂号|科室|去哪个科|挂什么科|看什么科|推荐科室|哪个医院|挂哪科)',
                r'.*?应该.*?看.*?什么科',
                r'.*?去.*?医院.*?哪个科'
            ],
            'drug_information': [
                r'.*?(药|药物|药品|用法|用量|怎么吃|服用|剂量|副作用|功效)',
                r'.*?这个.*?药.*?怎么用',
                r'.*?药物.*?信息'
            ],
            'prevention': [
                r'.*?(预防|防止|避免|注意|注意事项|忌口|饮食|保健|养生)',
                r'.*?怎么.*?预防',
                r'.*?需要.*?注意.*?什么'
            ]
        }
        
        # 匹配问题类型
        best_match = 'general'
        max_score = 0
        
        for q_type, patterns in question_patterns.items():
            for pattern in patterns:
                if re.search(pattern, question_lower):
                    best_match = q_type
                    max_score = 1
                    break
            if max_score > 0:
                break
        
        return best_match, keywords
    
    def _query_disease_symptoms(self, keywords: List[str]) -> Dict[str, Any]:
        """查询疾病症状"""
        results = {'diseases': [], 'symptoms': [], 'drugs': [], 'departments': [], 'relationships': []}
        
        for keyword in keywords:
            if keyword in self.diseases_data:  # 确认是疾病名称
                # 使用Neo4j查询
                if self.neo4j_service:
                    kg_result = self.neo4j_service.query_disease_symptoms(keyword)
                    if kg_result:
                        results['diseases'].append(kg_result)
                        results['symptoms'].extend(kg_result.get('symptoms', []))
        
        return results
    
    def _query_symptom_diseases(self, keywords: List[str]) -> Dict[str, Any]:
        """查询症状对应的疾病"""
        results = {'diseases': [], 'symptoms': [], 'drugs': [], 'departments': [], 'relationships': []}
        
        # 获取所有症状
        all_symptoms = set()
        for disease_info in self.diseases_data.values():
            all_symptoms.update(disease_info.get('symptoms', []))
        
        for keyword in keywords:
            if keyword in all_symptoms:  # 确认是症状
                if self.neo4j_service:
                    kg_result = self.neo4j_service.query_symptom_diseases(keyword)
                    if kg_result:
                        results['symptoms'].append(keyword)
                        results['diseases'].extend(kg_result.get('diseases', []))
        
        return results
    
    def _query_disease_treatment(self, keywords: List[str]) -> Dict[str, Any]:
        """查询疾病治疗方法"""
        results = {'diseases': [], 'symptoms': [], 'drugs': [], 'departments': [], 'relationships': []}
        
        for keyword in keywords:
            if keyword in self.diseases_data:  # 确认是疾病名称
                if self.neo4j_service:
                    kg_result = self.neo4j_service.query_disease_treatment(keyword)
                    if kg_result:
                        results['diseases'].append(kg_result)
                        results['drugs'].extend(kg_result.get('drugs', []))
        
        return results
    
    def _query_department_recommendation(self, keywords: List[str]) -> Dict[str, Any]:
        """查询科室推荐"""
        results = {'diseases': [], 'symptoms': [], 'drugs': [], 'departments': [], 'relationships': []}
        
        # 提取症状关键词
        symptoms = []
        all_symptoms = set()
        for disease_info in self.diseases_data.values():
            all_symptoms.update(disease_info.get('symptoms', []))
        
        for keyword in keywords:
            if keyword in all_symptoms:
                symptoms.append(keyword)
        
        if symptoms:
            if self.neo4j_service:
                kg_result = self.neo4j_service.query_department_recommendation(symptoms)
                if kg_result:
                    results['departments'] = kg_result.get('departments', [])
                    results['symptoms'] = kg_result.get('matched_symptoms', [])
        
        return results
    
    def _query_drug_information(self, keywords: List[str]) -> Dict[str, Any]:
        """查询药物信息"""
        results = {'diseases': [], 'symptoms': [], 'drugs': [], 'departments': [], 'relationships': []}
        
        # 提取所有药物名称
        all_drugs = set()
        for disease_info in self.diseases_data.values():
            for drug in disease_info.get('drugs', []):
                all_drugs.add(drug.get('name', ''))
        
        for keyword in keywords:
            if keyword in all_drugs:
                if self.neo4j_service:
                    kg_result = self.neo4j_service.query_drug_information(keyword)
                    if kg_result:
                        results['drugs'].append(kg_result)
                        results['diseases'].extend(kg_result.get('treats_diseases', []))
        
        return results
    
    def _query_disease_symptoms_enhanced(self, keywords: List[str]) -> Dict[str, Any]:
        """增强的疾病症状查询"""
        if not keywords:
            return {}
        
        results = []
        for keyword in keywords:
            if keyword in self.diseases_data:
                disease_info = self.diseases_data[keyword]
                results.append({
                    'disease': keyword,
                    'symptoms': disease_info.get('symptoms', []),
                    'description': disease_info.get('description', ''),
                    'severity': disease_info.get('severity', '一般'),
                    'contagious': disease_info.get('contagious', False)
                })
        
        return {
            'results': results,
            'question_type': 'disease_symptoms',
            'confidence': 0.85 if results else 0.3
        }

    def _query_symptom_diseases_enhanced(self, keywords: List[str]) -> Dict[str, Any]:
        """增强的症状对应疾病查询"""
        if not keywords:
            return {}
        
        symptom_disease_map = {}
        for disease_name, disease_info in self.diseases_data.items():
            symptoms = disease_info.get('symptoms', [])
            for symptom in symptoms:
                if any(keyword in symptom.lower() for keyword in [k.lower() for k in keywords]):
                    if symptom not in symptom_disease_map:
                        symptom_disease_map[symptom] = []
                    symptom_disease_map[symptom].append({
                        'disease': disease_name,
                        'description': disease_info.get('description', ''),
                        'severity': disease_info.get('severity', '一般'),
                        'match_score': self._calculate_symptom_match_score(symptom, keywords)
                    })
        
        # 按匹配度排序
        for symptom in symptom_disease_map:
            symptom_disease_map[symptom].sort(key=lambda x: x['match_score'], reverse=True)
        
        return {
            'results': list(symptom_disease_map.values()),
            'symptoms': list(symptom_disease_map.keys()),
            'question_type': 'symptom_diseases',
            'confidence': 0.8 if symptom_disease_map else 0.4
        }

    def _query_disease_treatment_enhanced(self, keywords: List[str]) -> Dict[str, Any]:
        """增强的疾病治疗查询"""
        if not keywords:
            return {}
        
        results = []
        for keyword in keywords:
            if keyword in self.diseases_data:
                disease_info = self.diseases_data[keyword]
                drugs = disease_info.get('drugs', [])
                treatment_plan = {
                    'disease': keyword,
                    'drugs': drugs,
                    'treatment_duration': disease_info.get('treatment_duration', '因人而异'),
                    'lifestyle_advice': disease_info.get('lifestyle_advice', []),
                    'warning_signs': disease_info.get('warning_signs', [])
                }
                results.append(treatment_plan)
        
        return {
            'results': results,
            'question_type': 'disease_treatment',
            'confidence': 0.9 if results else 0.3
        }

    def _query_department_recommendation_enhanced(self, keywords: List[str]) -> Dict[str, Any]:
        """增强的科室推荐查询"""
        if not keywords:
            return {}
        
        department_map = {}
        for disease_name, disease_info in self.diseases_data.items():
            if any(keyword.lower() in disease_name.lower() for keyword in keywords):
                departments = disease_info.get('departments', [])
                symptoms = disease_info.get('symptoms', [])
                for dept in departments:
                    if dept not in department_map:
                        department_map[dept] = {
                            'diseases': [],
                            'symptoms': [],
                            'priority': 0
                        }
                    department_map[dept]['diseases'].append(disease_name)
                    department_map[dept]['symptoms'].extend(symptoms)
                    department_map[dept]['priority'] += 1
        
        # 按优先级排序
        sorted_departments = sorted(department_map.items(), key=lambda x: x[1]['priority'], reverse=True)
        
        return {
            'departments': [dept[0] for dept in sorted_departments],
            'department_details': sorted_departments,
            'question_type': 'department_recommendation',
            'confidence': 0.85 if sorted_departments else 0.4
        }

    def _query_drug_information_enhanced(self, keywords: List[str]) -> Dict[str, Any]:
        """增强的药物信息查询"""
        if not keywords:
            return {}
        
        drug_results = []
        for disease_name, disease_info in self.diseases_data.items():
            drugs = disease_info.get('drugs', [])
            for drug in drugs:
                if isinstance(drug, dict):
                    drug_name = drug.get('name', '')
                    if any(keyword.lower() in drug_name.lower() for keyword in keywords):
                        drug_info = {
                            'drug': drug_name,
                            'usage': drug.get('usage', '遵医嘱'),
                            'dosage': drug.get('dosage', '按说明书服用'),
                            'side_effects': drug.get('side_effects', []),
                            'contraindications': drug.get('contraindications', []),
                            'treats_diseases': [disease_name]
                        }
                        drug_results.append(drug_info)
        
        return {
            'drugs': drug_results,
            'question_type': 'drug_information',
            'confidence': 0.9 if drug_results else 0.3
        }

    def _query_prevention_enhanced(self, keywords: List[str]) -> Dict[str, Any]:
        """增强的预防建议查询"""
        if not keywords:
            return {}
        
        prevention_results = []
        for keyword in keywords:
            if keyword in self.diseases_data:
                disease_info = self.diseases_data[keyword]
                prevention_info = {
                    'disease': keyword,
                    'prevention_methods': disease_info.get('prevention', []),
                    'lifestyle_advice': disease_info.get('lifestyle_advice', []),
                    'dietary_advice': disease_info.get('dietary_advice', []),
                    'warning_signs': disease_info.get('warning_signs', [])
                }
                prevention_results.append(prevention_info)
        
        return {
            'results': prevention_results,
            'question_type': 'prevention',
            'confidence': 0.8 if prevention_results else 0.4
        }

    def _query_general_knowledge_enhanced(self, question: str, keywords: List[str]) -> Dict[str, Any]:
        """增强的通用知识查询"""
        relevant_diseases = []
        
        # 基于关键词查找相关疾病
        for disease_name, disease_info in self.diseases_data.items():
            score = 0
            for keyword in keywords:
                if keyword.lower() in disease_name.lower():
                    score += 2
                for symptom in disease_info.get('symptoms', []):
                    if keyword.lower() in symptom.lower():
                        score += 1
            
            if score > 0:
                relevant_diseases.append({
                    'disease': disease_name,
                    'description': disease_info.get('description', ''),
                    'symptoms': disease_info.get('symptoms', []),
                    'relevance_score': score
                })
        
        # 按相关度排序
        relevant_diseases.sort(key=lambda x: x['relevance_score'], reverse=True)
        
        return {
            'results': relevant_diseases[:3],  # 返回最相关的3个疾病
            'question_type': 'general',
            'confidence': 0.7 if relevant_diseases else 0.2
        }

    def _fallback_kg_query(self, question: str, keywords: List[str]) -> Dict[str, Any]:
        """知识图谱查询回退机制"""
        # 使用基础查询作为回退
        return self._query_general_knowledge_enhanced(question, keywords)

    def _calculate_symptom_match_score(self, symptom: str, keywords: List[str]) -> float:
        """计算症状匹配分数"""
        score = 0.0
        symptom_lower = symptom.lower()
        
        for keyword in keywords:
            keyword_lower = keyword.lower()
            if keyword_lower in symptom_lower:
                score += len(keyword_lower) / len(symptom_lower)
            elif symptom_lower in keyword_lower:
                score += len(symptom_lower) / len(keyword_lower)
        
        return min(score, 1.0)

    def _validate_kg_results(self, results: Dict[str, Any]) -> bool:
        """验证知识图谱查询结果的有效性"""
        if not results:
            return False
        
        confidence = results.get('confidence', 0.0)
        if confidence < 0.3:
            return False
        
        # 检查结果内容是否有效
        for key, value in results.items():
            if isinstance(value, list) and len(value) > 0:
                return True
            elif isinstance(value, dict) and value:
                return True
        
        return False

    def _query_general_knowledge(self, keywords: List[str]) -> Dict[str, Any]:
        """通用知识查询"""
        results = {'diseases': [], 'symptoms': [], 'drugs': [], 'departments': [], 'relationships': []}
        
        if keywords:
            # 使用复杂关系查询
            if self.neo4j_service:
                kg_result = self.neo4j_service.query_complex_relationship(keywords)
                if kg_result:
                    results['relationships'] = kg_result
                
                # 提取相关信息
                for rel in kg_result:
                    if rel.get('disease'):
                        results['diseases'].append(rel['disease'])
                    if rel.get('symptom'):
                        results['symptoms'].append(rel['symptom'])
                    if rel.get('department'):
                        results['departments'].append(rel['department'])
        
        return results
    
    def _generate_knowledge_graph_answer(self, question: str, kg_results: Dict[str, Any]) -> str:
        """
        增强的知识图谱答案生成
        Enhanced knowledge graph answer generation
        
        Args:
            question: 用户问题
            kg_results: 知识图谱查询结果
            
        Returns:
            生成的答案
        """
        if not kg_results:
            return ""
        
        question_lower = question.lower()
        answer_parts = []
        confidence = kg_results.get('confidence', 0.0)
        
        # 处理疾病相关问题
        if kg_results.get('diseases'):
            for disease_info in kg_results['diseases']:
                if isinstance(disease_info, dict):
                    disease_name = disease_info.get('disease') or disease_info.get('name')
                    description = disease_info.get('description', '')
                    symptoms = disease_info.get('symptoms', [])
                    drugs = disease_info.get('drugs', [])
                    
                    # 根据问题类型生成不同的答案
                    if any(word in question_lower for word in ['症状', '表现']):
                        # 症状查询
                        if symptoms:
                            symptoms_str = '、'.join(symptoms)
                            answer_parts.append(f"{disease_name}的常见症状包括：{symptoms_str}。")
                        if description:
                            answer_parts.append(f"{description}")
                    elif any(word in question_lower for word in ['治疗', '用药']):
                        # 治疗查询
                        if drugs:
                            drugs_info = []
                            for drug in drugs:
                                if isinstance(drug, dict):
                                    drug_name = drug.get('name', '')
                                    usage = drug.get('usage', '')
                                    if drug_name:
                                        if usage:
                                            drugs_info.append(f"{drug_name}（{usage}）")
                                        else:
                                            drugs_info.append(drug_name)
                            if drugs_info:
                                drugs_str = '、'.join(drugs_info)
                                answer_parts.append(f"{disease_name}的常用药物包括：{drugs_str}。")
                    else:
                        # 通用介绍
                        if description:
                            answer_parts.append(f"关于{disease_name}：{description}。")

        # 处理症状相关问题
        if kg_results.get('symptoms') and any(word in question_lower for word in ['可能是', '什么病']):
            symptoms_mentioned = [s for s in kg_results['symptoms'] if isinstance(s, str)]
            if symptoms_mentioned and kg_results.get('diseases'):
                # 从疾病结果中提取疾病名称
                disease_names = []
                for disease in kg_results['diseases']:
                    if isinstance(disease, dict):
                        disease_names.extend(disease.get('diseases', []))
                    elif isinstance(disease, str):
                        disease_names.append(disease)
                
                if disease_names:
                    symptoms_str = '、'.join(symptoms_mentioned)
                    diseases_str = '、'.join([d.get('name', d) if isinstance(d, dict) else d for d in disease_names[:5]])
                    answer_parts.append(f"出现{symptoms_str}症状可能与以下疾病相关：{diseases_str}。")

        # 处理科室推荐
        if kg_results.get('departments'):
            departments = kg_results['departments']
            if departments and any(word in question_lower for word in ['挂号', '科室', '去哪']):
                departments_str = '、'.join(departments)
                matched_symptoms = kg_results.get('matched_symptoms', [])
                if matched_symptoms:
                    symptoms_str = '、'.join(matched_symptoms)
                    answer_parts.append(f"根据您描述的{symptoms_str}症状，建议您可以考虑挂以下科室：{departments_str}。")
                else:
                    answer_parts.append(f"建议您可以考虑挂以下科室：{departments_str}。")

        # 处理药物信息
        if kg_results.get('drugs'):
            for drug_info in kg_results['drugs']:
                if isinstance(drug_info, dict):
                    drug_name = drug_info.get('drug')
                    usage = drug_info.get('usage', '')
                    indication = drug_info.get('indication', '')
                    treats_diseases = drug_info.get('treats_diseases', [])
                    
                    if drug_name:
                        drug_desc = f"{drug_name}"
                        if usage:
                            drug_desc += f"，用法：{usage}"
                        if indication:
                            drug_desc += f"，适应症：{indication}"
                        if treats_diseases:
                            diseases_str = '、'.join(treats_diseases)
                            drug_desc += f"，可用于治疗：{diseases_str}"
                        answer_parts.append(drug_desc + "。")

        # 处理复杂关系
        if kg_results.get('relationships') and not answer_parts:
            relationships = kg_results['relationships']
            if relationships:
                # 按疾病分组
                disease_groups = {}
                for rel in relationships:
                    disease = rel.get('disease')
                    if disease:
                        if disease not in disease_groups:
                            disease_groups[disease] = {
                                'symptoms': set(),
                                'departments': set(),
                                'description': rel.get('disease_description', '')
                            }
                        if rel.get('symptom'):
                            disease_groups[disease]['symptoms'].add(rel['symptom'])
                        if rel.get('department'):
                            disease_groups[disease]['departments'].add(rel['department'])
                
                # 生成综合答案
                for disease, info in disease_groups.items():
                    disease_answer = f"关于{disease}："
                    if info['description']:
                        disease_answer += info['description'] + "。"
                    if info['symptoms']:
                        symptoms_str = '、'.join(list(info['symptoms']))
                        disease_answer += f"常见症状包括：{symptoms_str}。"
                    if info['departments']:
                        departments_str = '、'.join(list(info['departments']))
                        disease_answer += f"建议就诊科室：{departments_str}。"
                    answer_parts.append(disease_answer)

        # 组合答案
        if answer_parts:
            final_answer = ' '.join(answer_parts)
            # 添加置信度提示
            if confidence < 0.7:
                final_answer += " 请注意：此回答仅供参考，具体诊断请以医生意见为准。"
            # 添加医学建议
            if not any(word in final_answer for word in ['建议咨询', '请就医']):
                final_answer += "如果症状持续或加重，建议及时就医咨询专业医生。"
            return final_answer

        return ""
    
    def generate_answer(self, question: str, context: str = "", max_length: int = 512, 
                       session_id: str = "", user_feedback: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        根据问题和内置医疗知识生成答案
        Generate answer based on the question and internal medical knowledge
        
        Args:
            question: 用户问题
            context: 上下文信息
            max_length: 最大答案长度
            session_id: 会话ID
            user_feedback: 用户反馈信息
            
        Returns:
            包含答案、置信度、来源等信息的字典
        """
        self.query_count += 1
        
        # 处理用户反馈
        if user_feedback and self.auto_learning_manager:
            self._process_user_feedback(user_feedback)
        
        # 快速回答机制 - 处理常见问题和问候语
        quick_answer = self._get_quick_answer(question)
        if quick_answer:
            return {
                'question': question,
                'answer': quick_answer,
                'source': 'quick_response',
                'score': 0.90,
                'session_id': session_id,
                'timestamp': datetime.now().isoformat()
            }
        
        # 尝试使用深度学习模型
        if self.use_deep_learning and self.model_loaded:
            try:
                dl_answer = self._generate_deep_learning_answer(question, context)
                if dl_answer and self._validate_answer(dl_answer):
                    return {
                        'question': question,
                        'answer': dl_answer,
                        'source': 'deep_learning',
                        'score': 0.85,
                        'session_id': session_id,
                        'timestamp': datetime.now().isoformat()
                    }
            except Exception as e:
                logging.warning(f"深度学习推理失败，回退到基础方法: {str(e)}")
        
        # 优先使用Neo4j知识图谱
        if self.use_neo4j and self.neo4j_service:
            try:
                kg_results = self._query_knowledge_graph(question)
                kg_answer = self._generate_knowledge_graph_answer(question, kg_results)
                
                if kg_answer and len(kg_answer.strip()) > 10:  # 确保答案质量
                    return {
                        'question': question,
                        'answer': kg_answer,
                        'source': 'knowledge_graph',
                        'score': 0.80,
                        'session_id': session_id,
                        'timestamp': datetime.now().isoformat()
                    }
            except Exception as e:
                logging.warning(f"知识图谱查询失败，回退到基础方法: {str(e)}")
        
        # 使用基础知识库方法
        basic_answer = self._generate_basic_answer(question, context)
        
        return {
            'question': question,
            'answer': basic_answer,
            'source': 'knowledge_base',
            'score': 0.75,
            'session_id': session_id,
            'timestamp': datetime.now().isoformat()
        }
    
    def _get_quick_answer(self, question: str) -> Optional[str]:
        """
        快速回答机制，处理常见问题和问候语
        Quick answer mechanism for common questions and greetings
        
        Args:
            question: 用户问题
            
        Returns:
            快速回答或None
        """
        # 问候语处理
        if "你好" in question or "您好" in question:
            return "我是一个智能助手，我可以回答你的问题。请输入你的问题。"
        
        if "谢谢" in question:
            return "不客气。"
        
        if "再见" in question:
            return "祝你生活愉快"
        
        # 常见疾病快速回答
        if "感冒" in question:
            return "感冒是一种常见的呼吸道疾病，通常由病毒引起。症状包括发热、咳嗽、流鼻涕等。建议多休息、多喝水，必要时可以服用感冒药物。如果症状严重或持续不改善，请及时就医。"
        
        if "胃炎" in question:
            return "胃炎是胃黏膜的炎症，常见症状包括胃痛、恶心、呕吐等。建议规律饮食，避免辛辣刺激食物，可适当服用胃黏膜保护剂。如果症状持续，请就医诊治。"
        
        return None
    
    def _generate_deep_learning_answer(self, question: str, context: str) -> str:
        """使用深度学习模型生成答案"""
        if not self.dl_trainer:
            raise ValueError("深度学习模型未加载")
            
        answer = self.dl_trainer.predict(question, context)
        return answer.strip()
    
    def _generate_basic_answer(self, question: str, context: str) -> str:
        """使用基础知识库生成答案"""
        question_lower = question.lower()
        
        # Check for disease-related questions
        for disease_name, disease_info in self.diseases_data.items():
            if disease_name.lower() in question_lower:
                symptoms = ', '.join(disease_info.get('symptoms', []))
                drugs = disease_info.get('drugs', [])
                drug_info = '; '.join([f"{drug['name']} ({drug['usage']})" for drug in drugs])
                
                answer = f"关于{disease_name}：{disease_info.get('description', '')}。"
                answer += f"常见症状包括：{symptoms}。"
                if drugs:
                    answer += f"常用药物有：{drug_info}。"
                
                # 添加科室推荐
                related_departments = self._find_related_departments(disease_info.get('symptoms', []))
                if related_departments:
                    depts_str = '、'.join(related_departments)
                    answer += f"建议就诊科室：{depts_str}。"
                
                return answer
        
        # Check for department-related questions
        for dept_name, dept_info in self.departments_data.items():
            if dept_name.lower() in question_lower or any(symptom.lower() in question_lower for symptom in dept_info.get('symptoms', [])):
                symptoms = ', '.join(dept_info.get('symptoms', []))
                answer = f"如果您有以下症状：{symptoms}，建议您前往{dept_name}就诊。"
                return answer
                
        # Check for symptom-related questions
        all_symptoms = set()
        for disease_info in self.diseases_data.values():
            all_symptoms.update(disease_info.get('symptoms', []))
            
        for symptom in all_symptoms:
            if symptom.lower() in question_lower:
                related_diseases = []
                for disease_name, disease_info in self.diseases_data.items():
                    if symptom in disease_info.get('symptoms', []):
                        related_diseases.append(disease_name)
                
                if related_diseases:
                    diseases_str = '、'.join(related_diseases)
                    answer = f"{symptom}可能与以下疾病相关：{diseases_str}。"
                    
                    # 添加科室推荐
                    related_departments = self._find_related_departments([symptom])
                    if related_departments:
                        depts_str = '、'.join(related_departments)
                        answer += f"建议就诊科室：{depts_str}。"
                    
                    answer += "建议您咨询医生以获得准确诊断。"
                    return answer
        
        # 推荐科室功能 - 当用户直接询问应该去哪个科室时
        if any(keyword in question_lower for keyword in ["挂哪个科", "看哪个科", "去哪个科", "推荐科室", "哪个科室", "应该挂号"]):
            answer = self._recommend_departments(question)
            if answer:
                return answer
        
        # 默认回答
        return "感谢您的提问。我是基于医疗知识库的智能问答系统。根据您的问题，我无法提供具体的医疗建议。如果您有健康方面的担忧，建议咨询专业医生或前往医院就诊。"
    
    def _validate_answer(self, answer: str) -> bool:
        """验证答案质量"""
        if not answer or len(answer.strip()) < 5:
            return False
            
        # 检查是否包含有害内容（简化实现）
        harmful_keywords = ['自杀', '死亡', '危险', '毒性']
        for keyword in harmful_keywords:
            if keyword in answer:
                return False
                
        return True
    
    def _process_user_feedback(self, feedback: Dict[str, Any]):
        """处理用户反馈"""
        try:
            question = feedback.get('question', '')
            predicted_answer = feedback.get('predicted_answer', '')
            correct_answer = feedback.get('correct_answer', '')
            score = feedback.get('score', 0.0)
            feedback_text = feedback.get('feedback', '')
            
            if self.auto_learning_manager:
                self.auto_learning_manager.add_feedback(
                    question, predicted_answer, correct_answer, score, feedback_text
                )
                self.feedback_count += 1
                
        except Exception as e:
            logging.error(f"处理用户反馈失败: {str(e)}")
    
    def add_feedback(self, question: str, predicted_answer: str, 
                    correct_answer: str, score: float, feedback: str = ""):
        """添加用户反馈（向后兼容）"""
        feedback_data = {
            'question': question,
            'predicted_answer': predicted_answer,
            'correct_answer': correct_answer,
            'score': score,
            'feedback': feedback
        }
        self._process_user_feedback(feedback_data)
    
    def get_model_stats(self) -> Dict[str, Any]:
        """获取模型统计信息"""
        stats = {
            'query_count': self.query_count,
            'feedback_count': self.feedback_count,
            'use_deep_learning': self.use_deep_learning,
            'use_neo4j': self.use_neo4j,
            'model_loaded': self.model_loaded,
            'diseases_count': len(self.diseases_data),
            'departments_count': len(self.departments_data)
        }
        
        # 添加自主学习状态
        if self.auto_learning_manager:
            learning_status = self.auto_learning_manager.get_learning_status()
            stats['learning_status'] = learning_status
            
        return stats
    
    def train_model(self, force_retrain: bool = False) -> bool:
        """训练或更新模型"""
        if not self.use_deep_learning:
            logging.warning("深度学习功能未启用")
            return False
            
        if not self.auto_learning_manager:
            logging.error("自主学习管理器未初始化")
            return False
            
        if force_retrain:
            return self.auto_learning_manager.force_retrain("manual_request")
        else:
            # 检查是否满足自动训练条件
            learning_status = self.auto_learning_manager.get_learning_status()
            if not learning_status['is_learning']:
                self.auto_learning_manager.start_autonomous_learning()
                return True
            else:
                logging.info("模型正在训练中")
                return False
    
    def evaluate_model(self, test_questions: Optional[List[Dict[str, str]]] = None) -> Dict[str, Any]:
        """评估模型性能"""
        if not self.use_deep_learning or not self.evaluator:
            return {'error': '深度学习功能未启用'}
            
        # 使用默认测试问题或用户提供的问题
        if test_questions is None:
            test_questions = self._get_default_test_questions()
            
        predictions = []
        references = []
        
        for item in test_questions:
            question = item['question']
            expected_answer = item['answer']
            context = item.get('context', '')
            
            # 生成预测
            result = self.generate_answer(question, context)
            predicted_answer = result['answer']
            
            predictions.append(predicted_answer)
            references.append(expected_answer)
            
        # 计算评估指标
        if predictions and references:
            evaluation_result = self.evaluator.evaluate_batch(predictions, references)
            return evaluation_result
        else:
            return {'error': '没有有效的测试数据'}
    
    def _get_default_test_questions(self) -> List[Dict[str, str]]:
        """获取默认测试问题"""
        return [
            {
                'question': '感冒有什么症状？',
                'answer': '感冒的常见症状包括：发热、咳嗽、流鼻涕、头痛、乏力、咽喉痛。',
                'context': '疾病症状查询'
            },
            {
                'question': '胃痛应该挂什么科？',
                'answer': '如果您有胃痛的症状，建议您可以考虑前往消化内科就诊。',
                'context': '科室推荐'
            },
            {
                'question': '高血压用什么药？',
                'answer': '治疗高血压可以使用硝苯地平，用法：一次10mg，一日3次。扩张血管，降低血压',
                'context': '药物治疗'
            }
        ]

    def _find_related_departments(self, symptoms):
        """
        根据症状列表查找相关科室
        Find related departments based on symptoms list
        """
        related_departments = []
        
        for symptom in symptoms:
            for dept_name, dept_info in self.departments_data.items():
                if symptom in dept_info.get('symptoms', []):
                    # 避免重复添加科室
                    if dept_name not in related_departments:
                        related_departments.append(dept_name)
        
        return related_departments

    def _recommend_departments(self, question):
        """
        根据问题内容推荐科室
        Recommend departments based on question content
        """
        question_lower = question.lower()
        matched_departments = []
        
        # 根据科室症状关键词匹配
        for dept_name, dept_info in self.departments_data.items():
            symptoms = dept_info.get('symptoms', [])
            # 如果科室有50%以上的症状关键词在问题中出现，则推荐该科室
            matched_symptoms = [symptom for symptom in symptoms if symptom.lower() in question_lower]
            if len(matched_symptoms) >= len(symptoms) * 0.5 or len(matched_symptoms) >= 3:
                matched_departments.append(dept_name)
        
        if matched_departments:
            depts_str = '、'.join(matched_departments)
            return f"根据您的症状描述，建议您可以考虑挂以下科室：{depts_str}。"
        
        # 如果没有明确匹配，提供常见科室推荐
        common_depts = ["内科", "外科", "急诊科"]
        available_common_depts = [dept for dept in common_depts if dept in self.departments_data]
        if available_common_depts:
            depts_str = '、'.join(available_common_depts)
            return f"如果不确定具体科室，您可以先考虑挂以下常见科室：{depts_str}，医生会根据具体情况为您安排。"
        
        return None

# Global instance
medical_model = MedicalQAModel()